"""
#Copyright (c) 2008 Andrew Tamoney tamoneya AT gmail
#
#Permission is hereby granted, free of charge, to any person
#obtaining a copy of this software and associated documentation
#files (the "Software"), to deal in the Software without
#restriction, including without limitation the rights to use,
#copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the
#Software is furnished to do so, subject to the following
#conditions:
#
#The above copyright notice and this permission notice shall be
#included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
#OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
#WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#OTHER DEALINGS IN THE SOFTWARE.
"""
import random
import time

#globals
WORDS = {}
alphabet = {}
user = []
result = []
total = 0
board = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]

def pickletter():
	"""pick a random letter from 'alphabet' generated from dictionary"""
	global total
	global alphabet
	num = random.randint(0,total-1)
	for key in alphabet.keys():
		if num < alphabet[key]:
			return key
		else:
			num = num - alphabet[key]

def read_dictionary(myfile):
	"""Read the file for words for the dictionary."""
	myfile.readline() #The first line of mozilla dictionary is number of words
	for word in myfile.readlines():
		if (word.find('/') > 0):
			word = word[:word.find('/')]
		if (word.find('\\') > 0):
			word = word[:word.find('\\')]
		to_add = word.lower().strip()
		if len(to_add) > 2: 
			add_word(to_add)
	

def add_word(word):
	""" add a word and all of its partial words to the dictionary then add the letters to the alphabet"""
	global WORDS
	global alphabet
	global total
	WORDS[word] = True
	#add partials
	for i in range(2,len(word)):
		partial = word[:i]
		if not WORDS.has_key(partial):
			WORDS[partial] = 0
	#add letters
	for i in range(len(word)):
		if word[i].isalpha():
			total = total + 1
			if alphabet.has_key(word[i]):
				alphabet[word[i]] = alphabet[word[i]] + 1
			else:
				alphabet[word[i]] = 1

def make_board():
	"""place 16 letters into 4X4 grid"""
	#pick 16 letters
	letters = ""
	for i in range(16):
		letters += pickletter()
	letters = letters.lower()
	# all q's are automatically follwed by u's in Word Mix  When filling it grid it is easier to work with single letters
	for i in range(4):
		for j in range(4):
			# all q's are automatically follwed by u's in Word Mix. When filling it grid it is easier to work with single letters and to fill in the u's inside the for loop
			board[i][j] = letters[j+(4*i)].replace('q', 'qu')
	
def show():
	"""Print board for user in nice format"""	
	for row in board:
		print row[0] + row[1] + row[2] + row[3] + "\n"
		
def play():
	"""Display and Solve a Word Mix puzzle"""	
	start = time.time()
	global result	
	result = []
	#make dictionary
	try:
		WORDS["apple"]
	except KeyError:
		dict = open('english.dict','r') #this is the windows relative file location.  Use '/usr/lib/python2.5/en-US.dic' if using linux
		read_dictionary(dict)
	make_board()
	show()
	#get result
	result = list(set(find_words(board)))
	#input("Press 1 followed by enter for results")
	#print result

def find_words(board):
	"""return a list of all words on the board"""
	found = []
	for i in range(4):
		for j in range(4):
			found.extend(permutate(board, i, j, board[i][j], []))
	return found

def init():
	dict = open('english.dict','r') #this is the windows relative file location.  Use '/usr/lib/python2.5/en-US.dic' if using linux
	read_dictionary(dict)
def newgame():
	global result, user
	result = user = []
	make_board()
	result = list(set(find_words(board)))
def guess(word):
	"""
	allow user to guess at words.
	if word is valid add word to global variable 'user'
	"""
	global result
	global user
	if(result.count(word.lower().strip()) > 0) and (user.count(word.lower().strip()) == 0):
		user.insert(0,word.lower().strip())
		return True
	else:
		return False
		
def score(answer):
	"""Not the same values as Boggle.  This makes the game different.  Reduces TM issues.
	making it a simple mathematical relationship makes is nicer since I dont need a bunch of ifs"""
	pts = 0
	for a in answer:
		pts = pts + (len(a)*len(a))
	return pts

def permutate(board,i, j, partial, found):
		global WORDS
		for ni, nj in adjacent(board, i, j):
			next = board[ni][nj]
			word = partial + next
			if len(word) > 2 and WORDS.has_key(word) and WORDS[word]:
				found.append(word)
			if WORDS.has_key(word):
				old_val = board[i][j] #store value
				board[i][j] = '' #remove value so that I can't use it again in word
				found = permutate(board ,ni, nj, word, found)
				board[i][j] = old_val #replace value so board is not recursively destroyed
		return found	

def adjacent(board, i, j):
	"""Return list of all adjacent squares in the form (i,j)"""
	next = []	
	"""add valid squares to list"""
	for a in range(i-1, i+2):
		for b in range(j-1, j+2):
			if (0 <= a <4) and (0 <= b <4) and board[a][b] and (not((i == a) and (j == b))):
				next.append((a,b))
	return next
	
def lessthan(num):
	global result
	i = -1
	while i < 0 or i > num:
		play()
		i = len(result)
		
def large():
	global result
	i = 0
	while 1==1:
		result = []
		try:
			WORDS["apple"]
		except KeyError:
			dict = open('english.dict','r') #this is the windows relative file location.  Use '/usr/lib/python2.5/en-US.dic' if using linux
			read_dictionary(dict)
		make_board()
		result = list(set(find_words(board)))
		if len(result) > i:
			i = len(result)
			show()
			print i
